import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
import Common from '../utils/Common';
import Api from '../network/DataService';
import Constants from '../constants/AppConstants';
import Header from '../components/Header';
import Footer from '../components/Footer';
import Nav from '../components/Nav';
import CheckoutElement from '../components/CheckoutElement';
import SelectProductElement from '../components/SelectProductElement';
import OrderElement from '../components/OrderElement';
import BillElement from '../components/BillElement';
import MemberElement from '../components/MemberElement';

var checkout=new Array();
var selectHomeIndex=-1;
export default class Home extends React.Component {
  	constructor(props) {
		super(props);
		
		if(Common.getCookie("USER")==undefined){
			location.href="login.html"
		}else{
			
	    	this.state = {
		      'member':{},
		      'products':[],
		      'mproducts':[],
		      'bills':[],
		      'username':Common.getCookie("USER"),
		      'userid':Common.getCookie("USERID"),
		      'storename':Common.getCookie("STORENAME"),
		    };
		}
	    this.bound_onKeyEnter = this.onKeyEnter.bind(this);

  	}
	//会员信息
	loadMember(str){
		var params={"leaguerId":str};
		Api.memberInfoQuery(params,function(result){

			var data=result.content
			this.setState({modalIsOpen:false,member:data});
		}.bind(this));
	}
	//商品列表
	loadData(type){
		var val=this.refs.pno.value;
		//type=1表示条码枪操作
		if(val.length<13&&type==1){
			return;
		}
		var params={"queryParamter":val.trim()};
		Api.productsQuery(params,function(result){

			var data=result.content.list;
			if(data.length>1){
				//弹出选择窗口
				var element=(<SelectProductElement data={data} handleSelectProduct={this.handleSelectProduct.bind(this)}/>);
 				this.setState({mproducts:data,modalIsOpen: true,element:element});

			}else{
				var products=this.formatProducts(data);

				this.setState({
					products:products,
					amount:0
				})
			}
			$('#input').val("");

		}.bind(this));
	}
	//挂单
	hangBill(){
		var ids="";
		var amounts="";
		var products=this.state.products;
		var len=products.length;
		for(var i=0;i<len;i++){
			var p=products[i];
			var amount=p.amount!=undefined?p.amount:1;
			if(i==0){
				ids+=p.productId;
				amounts+=amount;
			}else{
				ids+="!"+p.productId;
				amounts+="!"+amount;
			}
		}
		var memberId=$('#memberId').val();
		if(memberId==""){
			memberId=0;
		}
		var params={'leaguerId':memberId,'productIdList':ids,'salesCountList':amounts};
		Api.hangOrder(params,function(result){

			if(result.content.hangId!=undefined){
				this.setState({products:[]});
				alert("挂单成功");
			}
		}.bind(this));
	}
	//提单
	loadBill(){
		Api.pickupListQuery({},function(result){

			var data=result.content.list
			if(data.length>0){
				//弹出选择窗口
				var element=(<BillElement data={data} handleSelectBill={this.handleSelectBill.bind(this)}/>);
 				this.setState({bills:data,modalIsOpen: true,element:element});
			}else{

			}

		}.bind(this));
	}
	//加载订单商品列表
	loadProductFromBill(id){

		Api.pickupDetailQuery({"hangId":id},function(result){

			var data=result.content.list
			this.setState({products:data,modalIsOpen:false});
		}.bind(this));
	}
	//重复编号的商品数量加1
	formatProducts(data){
		var products=this.state.products;
		var len=products.length;
		var index=-1;
		for(var i=0;i<len;i++){
			var p=products[i];
			//检查重复性
			if(p.productId==data[0].productId){
				index=i;
				break;
			}
		}
		if(index>-1){
			var p=products[index];
			if(p['amount']==undefined||p['amount']==1){
				p['amount']=2;
			}else{
				p['amount']++;
			}
			products[index]=p;
		}else{
			products=data.concat(products);
		}
		return products;
	}
	//结算信息
	handleCheckoutData(products){

		var len=products.length;
		var amount=0;
		var retailPrice=0;
		var promotionPrice=0;
		let isMember=false;
		if(this.state.member.leaguerId!=undefined){
			isMember=true;
		}
		for(var i=0;i<len;i++){
			var p=products[i];
			var a=p['amount']!=undefined?p['amount']:1;
			amount=Common.accAdd(amount,a);
			retailPrice=Common.accAdd(retailPrice,Common.accMul(p.retailPrice,a));
			if(isMember&&p.activityPrice!=undefined&&p.activityPrice!=0){
				//会员且存在活动价，以活动价为准.否则以零售价为准
				promotionPrice=Common.accAdd(promotionPrice,Common.accMul(p.activityPrice,a));
			}else{
				promotionPrice=Common.accAdd(promotionPrice,Common.accMul(p.retailPrice,a));
			}


		}
		var discountPrice=Common.subtr(retailPrice,promotionPrice);
		discountPrice=!isNaN(discountPrice)?discountPrice:0;
		checkout['amount']=amount;
		checkout['retailPrice']=retailPrice;
		checkout['promotionPrice']=promotionPrice;
		checkout['discountPrice']=discountPrice;

		//更新屏显
        if(typeof(python)!="undefined"){
			python.displayAblePrice(promotionPrice);
		}

		return checkout;
	}

	//左侧操作区
	handleNavAction(index){
		console.log(index);
		//会员识别
		if(index==0){
			var element=(<MemberElement handleMemberInfo={this.loadMember.bind(this)}/>);
 			this.setState({modalIsOpen: true,element:element});
		}
		if(index==1){

			this.numberUp();
		}
		if(index==2){
			this.numberDown();
		}
		//单品删除
		if(index==3){
			if(selectHomeIndex<0){
				return;
			}
			this.removeProduct(selectHomeIndex);
		}
		//整单删除
		if(index==4){
			this.setState({products:[],member:{}});
		}
		//挂单
		if(index==5){
			this.hangBill();
		}
		//提单
		if(index==6){
			this.loadBill();
		}
		//结算
		if(index==7){
			this.handlePayment();
		}

	}
	//商品选择窗口
	handleSelectProduct(index){

		var data=this.state.mproducts;
		if(data.length<=index){
			return;
		}
		var products=this.state.products;
		var array=new Array();
		array[0]=data[index];
		//洗刷
		products=this.formatProducts(array);
		this.setState({modalIsOpen: false,products:products,mproducts:[]});
	}
	//支付方式窗口
	handlePayment(){
		if(checkout['amount']==0){
			alert("无结算信息");
			return;
		}
		var element=(<CheckoutElement data={checkout} handleCheckout={this.handleCheckout.bind(this)}/>);
		this.setState({modalIsOpen: true,element:element});
	}

	//结算,生成订单信息
	handleCheckout(amount){
		//校验金额
		if(isNaN(amount)||amount<checkout['promotionPrice']){
			alert('请输入有效金额');
			return;
		}
		var a=amount.split('.');
		if(a.length>1&&a[1].length>1){
			alert('金额不能超过两位小数');
			return;
		}
		//更新窗口内容
		var orderId=new Date().getTime();
		//实收金额
		checkout['handMoney']=amount;
		var data={"amount":amount,"shouldAmount":checkout['promotionPrice'],"discountPrice":checkout['discountPrice'],"orderId":orderId};
		var element=(<OrderElement data={data} handleOrderBack={this.handleOrderBack.bind(this)} handleOrderDone={this.handleOrderDone.bind(this)}/>);
		this.setState({element:element});

	}
	//返回上一步
	handleOrderBack(){
		var element=(<CheckoutElement data={checkout} handleCheckout={this.handleCheckout.bind(this)}/>);
 		this.setState({element:element});
	}
	//订单完成，保存订单信息
	handleOrderDone(){
		var ids="";
		var amounts="";
		var products=this.state.products;
		var len=products.length;
		for(var i=0;i<len;i++){
			var p=products[i];
			var amount=p.amount!=undefined?p.amount:1;
			if(i==0){
				ids+=p.productId;
				amounts+=amount;
			}else{
				ids+="!"+p.productId;
				amounts+="!"+amount;
			}
		}
		var memberId=$('#memberId').val();
		if(memberId==""){
			memberId=0;
		}

		var params={
			"leaguerId":memberId,
			"totalPrice":checkout.promotionPrice,
			"totalPiece":checkout.amount,
			"totalDiscount":checkout.discountPrice,
			"paymentMethod":1,
			"productIdList":ids,
			"salesCountList":amounts
		};

		Api.settlementSaleOrder(params,function(result){
			console.log(result);
		});
		this.handlePrint();
		this.setState({modalIsOpen: false,products:[],member:{}});
	}
	//打印
	handlePrint(){
		let isMember=false;

		if(this.state.member.leaguerId!=undefined){
			isMember=true;
		}

		var html=Common.print(this.state.products,checkout,isMember);

		//调用打印机
		if(typeof(python)!="undefined"){
			python.printer(html);
		}
	}
	//提单选择
	handleSelectBill(index){
		var bills=this.state.bills;
		var bill=bills[index];
		this.loadProductFromBill(bill.hangId);
	}
	//数量增加
	numberUp(){
		var products=this.state.products;
		var len=products.length;
		if(len==0){
			return;
		}
		var p=products[len-1];
		if(p['amount']==undefined||p['amount']==1){
			p['amount']=2;
		}else{
			p['amount']++;
		}
		products[len-1]=p;
		this.setState({products:products});
	}
	//数量减少
	numberDown(){
		var products=this.state.products;
		var len=products.length;
		if(len==0){
			return;
		}
		var p=products[len-1];
		if(p['amount']==undefined||p['amount']==1){
			//删除最后一个
			products.pop();
		}else{
			p['amount']--;
			products[len-1]=p;
		}

		this.setState({products:products});
	}
	//双击编辑数量
	inputDoubleClick(index,e){
		$('#s'+(index-1)).hide();
		$('#v'+(index-1)).show().focus();
	}
	//光标移除数量文本框
	inputDone(index,e){
		$('#s'+(index-1)).show();
		$('#v'+(index-1)).hide();
		var val=e.target.value;
		if(val==""||val==0){
			val=1;
		}else if(parseInt(val)>99){
			val=99;
		}
		var products=this.state.products;
		var p=products[index-1];
		p.amount=parseInt(val);
		products[index-1]=p;
		//清除文本框值
		e.target.value="";
		this.setState({products:products});
	}
	//删除指定位置商品
	removeProduct(index){

		var products=this.state.products;
		if(products.length<index){
			return;
		}
		products.splice(index-1,1);
		this.setState({products:products});
	}
	openModal() {
	    this.setState({modalIsOpen: true});
	}
 	//modal打开后，计算位置
	afterOpenModal() {
	   var w=$('.ReactModal__Content').innerWidth();
	   var h=$('.ReactModal__Content').innerHeight();
	   var a=-w/2+"px";
	   var b=-h/2+"px";
	   $('.ReactModal__Content').css({"marginLeft":a,"marginTop":b});
	}
	requestClose(){
		this.setState({modalIsOpen: false});
	}
	closeModal() {
	    this.setState({modalIsOpen: false});
	}
	//键盘监听
	onKeyEnter(e){
		var code=event.keyCode||event.whitch;

		//只有在没有弹出窗口的情况下才触发动作
		if($(".ReactModal__Overlay").length>0){
			return;
		}

		//空白键
		if(code==32){
			this.loadData();
		}
		//shift键
		if(code==16){
			this.handlePayment();
		}
	}
	handelWindow(){
		 //首页页面元素宽度自适应
		$("#main_body").height($(document).height()-210);
		$(".message").width($(document).width()/100*55-15);
		$("#menu button").css("margin-top",($("#menu").height()-280)/8);
		$(".details div").width($(".details").width()/3-1);
		$(".member div").width($(".member").width()/3-1);
		$("#main_table").height($("#content").height()-55);
	}
	
  	componentDidUpdate(){
  		$("#input").focus();

  	}
	componentDidMount(){
        window.requestAnimationFrame(function() {
        	this.handelWindow();
        	$(window).resize(function() {
        		this.handelWindow();
			}.bind(this));
        	$("#input").focus();

			 //选择监听
			 $('#main_body').on('click','#productTable tr',function(){
			 	selectHomeIndex=$(this).data('index');
			 	/*
			 	if($(this).hasClass('active')){
			 		$(this).removeClass('active');
			 	}else{
			 		$(this).siblings().removeClass('active');
			 		$(this).addClass('active');
			 	}*/
			 	$(this).siblings().removeClass('active');
			 	$(this).addClass('active');

			 });
        }.bind(this));
        window.addEventListener("keyup",this.bound_onKeyEnter,false);


	}
	render() {
		var i=0;
		checkout=this.handleCheckoutData(this.state.products);

		var products=this.state.products.map(function(product){
			var amount=product.amount!=undefined?product.amount:1;
			var textId="s"+i;
			var valueId="v"+i;
			i++;
			return(
				<tr data-index={i}>
					<td>{i}</td>
					<td>{product.productName}</td>
					<td>{product.standard}</td>
					<td>{product.modelNum}</td>
					<td><span id={textId} onDoubleClick={this.inputDoubleClick.bind(this,i)}>{amount}</span><input id={valueId} className="hide" onBlur={this.inputDone.bind(this,i)}/></td>
					<td>{product.retailPrice}</td>
					<td>{product.activityPrice}</td>
					<td>{product.promotionPrice}</td>
					<td>{product.unit}</td>
					<td>{product.barcode}</td>
					<td>{product.productId}</td>
				</tr>
			)
		}.bind(this));
		return(
			<div>
				<Modal
			          isOpen={this.state.modalIsOpen}
			          onAfterOpen={this.afterOpenModal.bind(this)}
			          onRequestClose={this.requestClose.bind(this)}
			          shouldCloseOnOverlayClick={false}
			          style={Constants.MODAL_STYLE}>
			          {this.state.element}
			    </Modal>
				<Header storename={this.state.storename} userid={this.state.userid} username={this.state.username}/>
				<div id="main_body" className="main_body">
					<div id="content" className="left section">
						<div className="search_name">
							<label>商品编码/拼音码/条形码</label>
							<input style={{margin:'0 5px'}} id="input" type="text" name="pno" ref="pno" onChange={this.loadData.bind(this,1)}/>
							<button type="button" onClick={this.loadData.bind(this)}>查询</button>
						</div>
						<div id="main_table" className="main_table">
							<table id="productTable">
								<thead>
									<tr>
										<td>序号</td>
										<td>商品名称</td>
										<td>规格</td>
										<td>型号</td>
										<td>数量</td>
										<td>零售价</td>
										<td>活动价</td>
										<td>促销价</td>
										<td>单位</td>
										<td>条形码</td>
										<td>商品编号</td>
									</tr>
								</thead>
								<tbody>
									{products}
								</tbody>
							</table>
						</div>
					</div>
					<Nav handleAction={this.handleNavAction.bind(this)}/>
				</div>
				<Footer member={this.state.member} checkout={checkout} handleAction={this.handleNavAction.bind(this)}/>
			</div>
		)
	}
}
ReactDOM.render(
  <Home/>,
  document.getElementById('home-view')
);
